package com.example.sangong.rabbitmq;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class RabbitMqProducer {
    @Resource
    private RabbitTemplate rabbitTemplate;


    @Value("${rabbit-mq-batch-size:500}")
    private Integer batchSize;

    /**
     * 发送单条数据
     *
     * @param message
     */
    public void send(Object message) {
        sendList(Arrays.asList(message));
    }

    /**
     * 发送多条数据
     *
     * @param message
     */
    public void sendList(List<?> message) {
        if (CollectionUtil.isEmpty(message)) {
            log.info("消息为空：{}", message);
            return;
        }
        log.info("生产消息【{}】", message);
        List<? extends List<?>> partitions = Lists.partition(message, batchSize);
        for (List<?> partition : partitions) {
            rabbitTemplate.convertAndSend(RabbitMqConstant.NOTIFY_MSG_DIRECT_EXCHANGE,
                    RabbitMqConstant.NOTIFY_MSG, JSONUtil.toJsonStr(partition));
        }

    }

}
